<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .container{
            width: 590px;
            height: 590px;
            border:5px solid;
            position: relative;
            margin:0 auto;
        }
        .container div{
            width: 180px;
            height: 180px;
            position: absolute;
            background: gray;
            color: white;
            font-size: 30px;
            text-align: center;
            line-height: 180px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div style="left: 10px; top:10px;">1</div>
        <div style="left: 34%; top:10px;">2</div>
        <div style="left: 66.66%; top:10px;">3</div>
        <div style="left: 10px; top:33.33%;">4</div>
        <div style="left: 34%; top:33.33%;">5</div>
        <div style="left: 66.66%; top:33.33%;">6</div>
        <div style="left: 10px; top:66.66%;">7</div>
        <div style="left: 34%; top:66.66%;">8</div>
        <div style="left: 66.66%; top:66.66%;">9</div>
    </div>
    <script>
        var colorArr = ["black","red","blue","orange","pink","yellow","skyblue","green","yellowgreen"];
        var divs =  document.querySelectorAll(".container div");
        for(var i=0;i<divs.length;i++){
        //    console.log(  divs[i]);
            divs[i].style.backgroundColor = colorArr[i];
        }


        // 给每一个方块都绑定拖拽的事件。

        for(var i=0;i<divs.length;i++){
            divs[i].onmousedown = function(e){
                var x = e.clientX - this.offsetLeft;
                var y = e.clientY - this.offsetTop;
                // 当按下拖动的时候 那么 把这个被拖动的元素 放在最上层；
                this.style.zIndex = 10;
                // console.log(x,y);
                this.onmousemove = function(e){
                    var xx = e.clientX;
                    var yy = e.clientY;
                    // x  = e.clientX - this.offsetLeft
                    // xx -(e.clientX - this.offsetLeft)
                    this.style.left = xx - x + "px";
                    this.style.top = yy - y + "px";
                }
            }
            divs[i].onmouseup = function(){
                // 拖动结束了 
                this.style.zIndex = 0;
                this.onmousemove = null;
            }
        }


    </script>
</body>
</html>